1. models.py - 定义数据库模型
python
运行
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    interests = db.Column(db.String(200))
    # 用逗号分隔存储好友 ID
    friends = db.Column(db.String(200))
    browsing_history = db.Column(db.String(200))

    def get_friend_ids(self):
        return [int(friend_id) for friend_id in self.friends.split(',') if friend_id]

    def get_interests_list(self):
        return self.interests.split(',') if self.interests else []

    def get_browsing_history_list(self):
        return self.browsing_history.split(',') if self.browsing_history else []


class Content(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    type = db.Column(db.String(20))  # 内容类型，如 "friend_dynamic", "topic_discussion", "related_video"
    tags = db.Column(db.String(200))

    def get_tags_list(self):
        return self.tags.split(',') if self.tags else []









2. app.py - 主应用代码
python
运行
from flask import Flask, jsonify
from models import db, User, Content
import sqlite3

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db.init_app(app)


def calculate_similarity(user_interests, content_tags):
    common_tags = set(user_interests).intersection(set(content_tags))
    return len(common_tags) / len(set(user_interests).union(set(content_tags)))


def recommend_content(user_id, num_recommendations=3):
    with app.app_context():
        user = User.query.get(user_id)
        if not user:
            return []

        user_interests = user.get_interests_list()
        friend_ids = user.get_friend_ids()

        # 收集好友动态
        friend_dynamics = []
        for friend_id in friend_ids:
            # 这里可以根据实际情况从数据库获取好友动态
            # 为简化，我们假设好友动态就是内容的一部分
            friend_dynamic_contents = Content.query.filter_by(type="friend